package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class ImgTask {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 删除图片任务
     */
    //每天凌晨1点执行一次
    @Scheduled(cron = "0 0 1 * * ?")
    //每隔1分钟执行一次 测试用
    //@Scheduled(cron = "0 0/1 * * * ? ")
    public void deleteImg(){
        log.info("开始执行删除图片任务");
        Set savedFile = redisTemplate.opsForSet().members("savedFile");
        Set uploadFile = redisTemplate.opsForSet().members("uploadFile");
        for (Object o : uploadFile) {
            //如果上传的图片没有被保存，则删除
            if (!savedFile.contains(o)){
                aliOssUtil.delete(o.toString());
            }
        }
        //删除Redis中的数据
        redisTemplate.delete("uploadFile");
        redisTemplate.delete("savedFile");
    }
}
